package com.haier.service.impl;

import java.util.*;

import com.haier.constant.HpConstant;
import com.haier.entity.HpRandomColorHistory;
import com.haier.mapper.*;
import com.haier.vo.HpAreaAuditorVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haier.dto.hpConstantDto;
import com.haier.entity.HpConstantEntity;
import com.haier.service.IHpConstantService;
import com.haier.utils.EmptyUtils;
import com.haier.utils.GetUtils;
import com.haier.vo.ResponseVo;

/**
 * <p>
 * 常量 服务实现类
 * </p>
 *
 * @author luanxuecheng
 * @since 2020-07-01
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class HpConstantServiceImpl extends ServiceImpl<HpConstantMapper, HpConstantEntity>
		implements IHpConstantService {
	@Autowired
	private HpGardenMapper hpGardenMapper;
	@Autowired
	private HpAreaMapper hpAreaMapper;
	@Autowired
	private HpAreaAuditorMapper hpAreaAuditorMapper;
	@Autowired
	private HpConstantMapper hpConstantMapper;
	@Autowired
	private HpAuthorizerConfigMapper hpAuthorizerConfigMapper;
	@Autowired
	private HpRandomColorHistoryMapper hpRandomColorHistoryMapper;

	@Override
	public JSONObject findAll(JSONObject params) {
		JSONObject result = new JSONObject();
		List<Map<String, Object>> gardenList = hpGardenMapper.findByH5();
		if (!EmptyUtils.isEmpty(gardenList)) {
			for (int i = 0; i < gardenList.size(); i++) {
				Map<String, Object> garden = gardenList.get(i);
				Long id = GetUtils.getLong(garden.get("id"));
				List<Map<String, Object>> areaList = hpAreaMapper.findByH5(id);
				garden.put("areaList", areaList);
			}
		}
		result.put("gardenList", gardenList);
		return result;
	}

	@Override
	public List<HpAreaAuditorVo> findAuditorByAreaId(JSONObject params) {
		String areaId = params.getString("areaId");
		List<HpAreaAuditorVo> vo = hpAreaAuditorMapper.findByH5AreaId(areaId);
		if(!EmptyUtils.isEmpty(vo)){
			vo.forEach(p->{
				HpAreaAuditorVo effectiveAuthorizedPerson = hpAuthorizerConfigMapper.findEffectiveAuthorizedPerson(p.getJobNumber());
				if(!EmptyUtils.isEmpty(effectiveAuthorizedPerson)){
					p.setName(effectiveAuthorizedPerson.getName());
					p.setJobNumber(effectiveAuthorizedPerson.getJobNumber());
				}
			});
			return vo;
		}
		return null;
	}


	@Override
	public IPage page(hpConstantDto dto) {
		Page<HpConstantEntity> page = new Page<>(dto.getPageNo(), dto.getPageSize(), dto.getHasTotal());
		QueryWrapper queryWrapper = new QueryWrapper();
		return page(page, queryWrapper);
	}

	@Override
	public ResponseVo edit(JSONObject params) {
		String hpKey = params.getString("hpKey");
		String hpValue = params.getString("hpValue");
		HpConstantEntity hpConstantEntity = baseMapper.selectById(hpKey);
		if (!hpValue.matches(hpConstantEntity.getHpRegex())) {
			return ResponseVo.checkError("该数据不符合规范");
		}
		hpConstantEntity.setHpValue(hpValue);
		baseMapper.updateById(hpConstantEntity);
		return ResponseVo.success();
	}

	/**
	 * 保存或修改授权人等级
	 * @param params
	 * @return
	 */
	@Override
	public ResponseVo saveOrUpdateLevel(JSONObject params) {
		String authorizerLevel = params.getString("authorizerLevel");
		String passivityAuthorizerLevel = params.getString("passivityAuthorizerLevel");
		HpConstantEntity authorizerEntity = hpConstantMapper.selectById(HpConstant.CONSTANT_KEY_AUTHORIZER_LEVEL);//授权人等级
		HpConstantEntity passivityAuthorizerEntity = hpConstantMapper.selectById(HpConstant.CONSTANT_KEY_PASSIVITYAUTHORIZER_LEVEL);//被授权人等级
		//如果授权人等级不为空，更新
		if(authorizerEntity!=null){
			authorizerEntity.setHpValue(authorizerLevel);
			baseMapper.updateById(authorizerEntity);
		}else{
			//保存
			authorizerEntity = new HpConstantEntity();
			authorizerEntity.setHpKey(HpConstant.CONSTANT_KEY_AUTHORIZER_LEVEL);
			authorizerEntity.setHpValue(authorizerLevel);
			authorizerEntity.setHpDesc(HpConstant.CONSTANT_KEY_AUTHORIZER_DESC);
			baseMapper.insert(authorizerEntity);
		}
		//如果被授权人等级不为空，更新
		if(passivityAuthorizerEntity!=null){
			passivityAuthorizerEntity.setHpValue(passivityAuthorizerLevel);
			baseMapper.updateById(passivityAuthorizerEntity);
		}else{
			passivityAuthorizerEntity = new HpConstantEntity();
			passivityAuthorizerEntity.setHpKey(HpConstant.CONSTANT_KEY_PASSIVITYAUTHORIZER_LEVEL);
			passivityAuthorizerEntity.setHpValue(passivityAuthorizerLevel);
			passivityAuthorizerEntity.setHpDesc(HpConstant.CONSTANT_KEY_PASSIVITYAUTHORIZER_DESC);
			baseMapper.insert(passivityAuthorizerEntity);
		}
		return ResponseVo.success();
	}

	/**
	 * 查询授权人等级、被授权人等级
	 * @return
	 */
	@Override
	public ResponseVo selectAuthorizerLevel() {
		Map<String,Object> map = new HashMap<>();
		HpConstantEntity authorizerEntity = hpConstantMapper.selectById(HpConstant.CONSTANT_KEY_AUTHORIZER_LEVEL);//授权人等级
		HpConstantEntity passivityAuthorizerEntity = hpConstantMapper.selectById(HpConstant.CONSTANT_KEY_PASSIVITYAUTHORIZER_LEVEL);//被授权人等级
		String authorizerLevel = "";
		String passivityAuthorizerLevel = "";
		if(authorizerEntity!=null){
			authorizerLevel=authorizerEntity.getHpValue();
		}
		if(passivityAuthorizerEntity!=null){
			passivityAuthorizerLevel=passivityAuthorizerEntity.getHpValue();
		}
		map.put("authorizerLevel",authorizerLevel);
		map.put("passivityAuthorizerLevel",passivityAuthorizerLevel);
		return ResponseVo.success(map);
	}

	@Override
	public Integer getRandomNumber() {
		String date = GetUtils.getDateString(new Date(), "yyyy-MM-dd");
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("date_day", date);
		HpRandomColorHistory history = hpRandomColorHistoryMapper.selectOne(queryWrapper);
		if (!EmptyUtils.isEmpty(history)) {
			return history.getRandomId();
		}
		Random random = new Random();
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		String yesterday = GetUtils.getDateString(calendar.getTime(), "yyyy-MM-dd");
		QueryWrapper query = new QueryWrapper();
		query.eq("date_day", yesterday);
		HpRandomColorHistory historyData = hpRandomColorHistoryMapper.selectOne(query);
		HpConstantEntity number = hpConstantMapper.selectById("random_number");
		int s = random.nextInt(Integer.parseInt(number.getHpValue()))+1;
		if(!EmptyUtils.isEmpty(historyData)){
			while (historyData.getRandomId() == s){
				s = random.nextInt(Integer.parseInt(number.getHpValue()))+1;
			}
		}
		HpRandomColorHistory hpRandomColorHistory = new HpRandomColorHistory();
		hpRandomColorHistory.setRandomId(s);
		hpRandomColorHistory.setDateDay(date);
		hpRandomColorHistoryMapper.insert(hpRandomColorHistory);
		return s;
	}
}
